<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { getTrademarkListService } from '@/apis/product/trademark'
import type {
  TrademarkResponseData,
  Records,
  Trademark
} from '@/apis/product/trademark/type'
import type { UploadProps } from 'element-plus'
import {
  addTrademarkService,
  updateTrademarkService,
  deleteTrademarkService
} from '@/apis/product/trademark'

const pageNo = ref<number>(1)
const pageSize = ref<number>(3)
const total = ref<number>(0)
const trademarkList = ref<Records>([])
// 获取品牌列表
const getTrademarkList = async () => {
  const res: TrademarkResponseData = await getTrademarkListService(
    pageNo.value,
    pageSize.value
  )
  console.log(res)
  total.value = res.data.total
  trademarkList.value = res.data.records
}
// 当前页修改
const onPageChange = (val: number) => {
  pageNo.value = val
  getTrademarkList()
}
// 每页条数修改
const onSizeChange = (val: number) => {
  pageNo.value = 1
  pageSize.value = val
  getTrademarkList()
}
onMounted(() => {
  getTrademarkList()
})
// 表单
const formRef = ref()
// 表单数据
const formModel = ref<Trademark>({
  tmName: '',
  logoUrl: ''
})
// 表单规则
const rules = ref({
  tmName: [
    { required: true, message: '请输入品牌名称', trigger: 'blur' },
    {
      min: 2,
      max: 10,
      message: '品牌名称长度在 2 到 10 个字符',
      trigger: 'change'
    }
  ],
  logoUrl: [{ required: true, message: '请上传品牌图片', trigger: 'blur' }]
})

// 添加品牌
const dialogVisible = ref<boolean>(false)
const onAdd = () => {
  formModel.value = {
    tmName: '',
    logoUrl: ''
  }
  // 清除表单验证信息
  formRef.value?.clearValidate('tmName')
  formRef.value?.clearValidate('logoUrl')
  // nextTick(() => {
  //   formRef.value.clearValidate('tmName')
  //   formRef.value.clearValidate('logoUrl')
  // })
  pageNo.value = Math.ceil((total.value + 1) / pageSize.value)
  // console.log
  dialogVisible.value = true
}
// 编辑品牌
const onEdit = (row: Trademark) => {
  dialogVisible.value = true
  formModel.value = row
}
// 删除品牌
const onDelete = async (row: Trademark) => {
  await deleteTrademarkService(row.id as number)
  getTrademarkList()
  ElNotification({
    type: 'success',
    title: '删除成功',
    message: '删除品牌成功'
  })
}
// 上传图片
const beforeAvatarUpload: UploadProps['beforeUpload'] = async (raw) => {
  if (
    raw.type !== 'image/jpeg' &&
    raw.type !== 'image/png' &&
    raw.type !== 'image/gif'
  ) {
    await ElMessage.error('上传图片只能是 JPG/PNG/gif 格式!')
    return false
  } else if (raw.size / 1024 / 1024 > 4) {
    await ElMessage.error('上传图片大小不能超过 4MB!')
    return false
  }
  return true
}
const onUpload: UploadProps['onSuccess'] = (response) => {
  formModel.value.logoUrl = response.data
  // form清除表单验证信息
  formRef.value.clearValidate('logoUrl')
}
//确认按钮
const onConfirm = async () => {
  await formRef.value.validate()
  if (!formModel.value.id) {
    await addTrademarkService(formModel.value)
  } else {
    await updateTrademarkService(formModel.value)
  }
  getTrademarkList()
  ElMessage.success(formModel.value.id ? '修改成功' : '添加成功')
  dialogVisible.value = false
}
</script>

<template>
  <div class="trademark">
    <el-card>
      <el-button type="primary" icon="Plus" @click="onAdd">添加品牌</el-button>

      <!-- 表格 -->
      <el-table
        :data="trademarkList"
        border
        style="margin-top: 20px"
        size="large"
      >
        <el-table-column label="序号" type="index" width="80px" align="center">
        </el-table-column>
        <el-table-column
          label="品牌名称"
          prop="tmName"
          align="center"
        ></el-table-column>
        <el-table-column label="品牌LoGo">
          <template #default="{ row }">
            <img
              :src="
                row.logoUrl.substring(0, 7) === 'http://'
                  ? row.logoUrl
                  : `http://${row.logoUrl}`
              "
              alt=""
              style="width: 50px; height: 50px; object-fit: cover"
            />
          </template>
        </el-table-column>
        <el-table-column label="品牌操作">
          <template #default="{ row }">
            <el-button
              type="warning"
              circle
              icon="Edit"
              @click="onEdit(row)"
            ></el-button>
            <el-popconfirm
              title="你确认删除吗?"
              @confirm="onDelete(row)"
              icon="Warning"
            >
              <template #reference>
                <el-button type="danger" circle icon="Delete"></el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
        <template #empty>
          <el-empty description="暂无数据"></el-empty>
        </template>
      </el-table>

      <!-- 分页器 -->
      <el-pagination
        layout="prev, pager, next, jumper, ->, sizes, total"
        :total="total"
        :page-sizes="[3, 5, 10]"
        v-model:current-page="pageNo"
        v-model:page-size="pageSize"
        @current-change="onPageChange"
        @size-change="onSizeChange"
      />

      <!-- 添加、编辑弹框 -->
      <el-dialog
        :title="formModel.id ? '修改品牌' : '添加品牌'"
        v-model="dialogVisible"
      >
        <el-form
          label-width="80px"
          style="width: 80%"
          ref="formRef"
          :model="formModel"
          :rules="rules"
        >
          <el-form-item label="品牌名称" prop="tmName">
            <el-input v-model="formModel.tmName"></el-input>
          </el-form-item>
          <el-form-item label="品牌LOGO" prop="logoUrl">
            <el-upload
              class="avatar-uploader"
              :show-file-list="false"
              action="/api/admin/product/fileUpload"
              :on-success="onUpload"
              :before-upload="beforeAvatarUpload"
            >
              <img
                v-if="formModel.logoUrl"
                :src="formModel.logoUrl"
                class="avatar"
              />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button type="primary" @click="dialogVisible = false"
            >取消</el-button
          >
          <el-button type="primary" @click="onConfirm">确认</el-button>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
